from machine import Pin, UART
from ringbuffer import RingBuffer
from micropython import const
import time
from ui import *

import re

MAX_REPORT_TIMEOUT = const(5000)

class WaterLevel:

	def __init__(self, port):
		self.port = port
		self.uart = UART(port, 9600)
		self.uart.init(9600, timeout=10)	# 9600, 1byte about 1ms, wait for 10ms
		self.buffer = RingBuffer(10)
		self.last_report_tick = 0
		self.max = 400

	# return
	# False: no change
	# True: change, need read value
	def Check(self):
		# timeout check
		if time.ticks_diff(time.ticks_ms(), self.last_report_tick) > MAX_REPORT_TIMEOUT:
			value_change = None
		else:
			value_change = False

		count = self.uart.any()
		if count < 3:
			return value_change
			# At lease 3 bytes in buffer (For example:0mm)

		while 1:		# maybe too many data in UART RX buffer
			data = self.uart.readline()
			if data:
				number_string = re.search(b'^\d+', data)
				if number_string:
					number = int(number_string.group(0))
					if number > self.max:
						break
					value_change = self.buffer.InsertData(number, True)
					self.last_report_tick = time.ticks_ms()

			else:
				break
		
		return value_change


	def GetValue(self):
		return self.buffer.GetAverage()

	def SetMax(self, val):
		self.max = val
